package com.domain.oa.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Configuration
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 存放结果
        ResultVo resultVo = new ResultVo();

        if(request.getMethod().equals("OPTIONS")) {
            log.info("是OPTIONS！！！无条件放行");
            return true;
        }

        // 获取请求头中的token
        String token = request.getHeader("token");
        // 输出当前token到控制台
        log.info("token:[{}]", token);
        // 验证token是否合法
        if(token == null) {
            resultVo.setCode(400).setMsg("请登录之后访问...").setData(null);
        }else {
            if(JWTUtils.verifyToken(token) == 0){
                return true;
            }else {
                resultVo.setCode(400).setMsg("验证失败").setData(null);
            }
        }
        // 将map转化为json
        String json = new ObjectMapper().writeValueAsString(resultVo);
        // 设置相应类型以及编码
        response.setContentType("application/json;charset=utf-8");
        // 将信息响应给用户
        response.getWriter().println(json);
        // 结束本次拦截，不继续进行业务逻辑处理
        return false;
    }
}
